package shop.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import shop.dao.BaseOrderDao;
import shop.entity.BaseOrder;
import shop.entity.vo.OrderVO;
import shop.util.DBUtil;

public class BaseOrderDaoImpl implements BaseOrderDao {

	@Override
	public void add(BaseOrder order) {
		String sql = "INSERT INTO `interesting_shop_db`.`t_base_order`(`user_id`, `account`, `user_address`,  `amount`, `order_no`, `name`, `phone`) VALUES (?,?,?,?,?,?,?)";
		Object[] params = new Object[] {order.getUserId(),order.getAccount(),order.getUserAddress(),order.getAmount(),order.getOrderNo(),order.getName(),order.getPhone()};
		DBUtil.update(sql, params);
	}

	@Override
	public List<BaseOrder> findAll(int id) {
		List<BaseOrder> list = new ArrayList<>();
		String sql = "select * from t_base_order where user_id = "+id;
		ResultSet rs = DBUtil.query(sql, null);
		try {
			while(rs.next()) {
				String orderNo = rs.getString("order_no");
				Date createTime = rs.getTimestamp("create_time");
				double amount = rs.getDouble("amount");
				String status = rs.getString("status");
				BaseOrder order = new BaseOrder();
				order.setAmount(amount);
				order.setOrderNo(orderNo);
				order.setCreateTime(createTime);
				order.setStatus(status);
				list.add(order);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public void pay(double amount,int uid) {
		String sql = "update t_user set balance = balance-"+amount+" where id = "+uid;
		DBUtil.update(sql, null);
	}

	@Override
	public void consume(double amount,int uid) {
		String sql = "update t_user set consume = consume+"+amount+" where id = "+uid;
		DBUtil.update(sql, null);
	}

	@Override
	public List<OrderVO> findDetails(String orderNo) {
		List<OrderVO> list = new ArrayList<>();
		String sql = "select o.order_no,g.id gid,g.goods_name,g.file_name,g.price,i.buy_num,g.price*i.buy_num xiaoji from t_base_order o,t_goods g,t_user u,t_order_info i where o.order_no=i.order_no  and o.user_id=u.id and i.goods_id=g.id and o.order_no = "+orderNo;
		ResultSet rs = DBUtil.query(sql, null);
		try {
			while(rs.next()) {
				String orderNo1 = rs.getString("order_no");
				int gid = rs.getInt("gid");
				String goodsName = rs.getString("goods_name");
				String fileName = rs.getString("file_name");
				double price = rs.getDouble("price");
				int buyNum = rs.getInt("buy_num");
				double xiaoji = rs.getDouble("xiaoji");
				OrderVO vo = new OrderVO(orderNo1, gid, goodsName, fileName, price, buyNum, xiaoji);
				list.add(vo);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

}
